<template>
  <div id="login">
    <el-form :model="form" status-icon :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
      <h3 class="title">登录</h3>
      <el-form-item prop="username">
        <el-input type="text" v-model="form.username" autocomplete="off" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="form.password" autocomplete="off" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
        <el-button type="primary" @click="zhuce">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ validator: validateUsername, trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$http.post('https://youxuan-zua-api.tulan.wang/admin/ysf-user-info/login', { username: this.form.username, password: this.form.password })
              .then(response => {
                if (response.data.status==0) {
                  this.$router.push({ path: '/about' });
                } else {
                  this.$message.error(response.data.msg);
                }
              })
              .catch(error => {
                this.$message.error('网络错误');
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    zhuce(){
      this.$router.push({ path: '/register' });
    }
  }
};
</script>

<style scoped>
#login {
  width: 300px;
  margin: 150px auto;
}
.title {
  text-align: center;
}
</style>